package com.lby.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.lby.dao.MyBeanDao;
import com.lby.model.ScoreDimensionConfig;

/**
 * https://my.oschina.net/newchaos/blog/1641741
 * @author Administrator
 *
 */
@Service
public class LoadingCacheService {

	@Autowired
	private MyBeanDao myBeanDao;
	
	/*
	 * 单个cache实例
	 * LoadingCache<String, List<ScoreDimensionConfig>> configCache = CacheBuilder.newBuilder()
            .maximumSize(10000)//设置缓存上线
//            .expireAfterAccess(10, TimeUnit.MINUTES)//设置时间对象没有被读/写访问则对象从内存中删除
//            .expireAfterWrite(10, TimeUnit.SECONDS)//设置时间对象没有被写访问则对象从内存中删除
            .refreshAfterWrite(10, TimeUnit.SECONDS)//设置多少时间之后，刷新缓存
            //CacheLoader类 实现自动加载
            .build(new CacheLoader<String, List<ScoreDimensionConfig>>() {
                @Override
                public List<ScoreDimensionConfig> load(String key) {
                	System.out.println("fire load db.....");
                	
                	ScoreDimensionConfig config = myBeanDao.getConfigById(18L);
                	List<ScoreDimensionConfig> list = new ArrayList<ScoreDimensionConfig>();
                	list.add(config);
                	return list;
                }
            });*/
	
	
	//多个key，一个cache实例
	LoadingCache<String, Object> configCache = CacheBuilder.newBuilder()
            .maximumSize(10000)//设置缓存上线
//            .expireAfterAccess(10, TimeUnit.MINUTES)//设置时间对象没有被读/写访问则对象从内存中删除
//            .expireAfterWrite(10, TimeUnit.SECONDS)//设置时间对象没有被写访问则对象从内存中删除
            .refreshAfterWrite(10, TimeUnit.SECONDS)//设置多少时间之后，刷新缓存
            //CacheLoader类 实现自动加载
            .build(new CacheLoader<String, Object>() {
                @Override
                public Object load(String key) {
                	System.out.println("fire load db.....");
                	if(key.equals("config")) {
                		ScoreDimensionConfig config = myBeanDao.getConfigById(18L);
                    	List<ScoreDimensionConfig> list = new ArrayList<ScoreDimensionConfig>();
                    	list.add(config);
                    	return list;
                	} else {
                		
                	}
                	return null;
                	
                }
            });
	
	public List<ScoreDimensionConfig> getConfigList() {
		try {
			Object object = configCache.get("config");
			List<ScoreDimensionConfig> list = (List<ScoreDimensionConfig>) object;
			return list;
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		return Collections.emptyList(); 
	}
	
}
